from flask import Flask, render_template, request, jsonify, send_from_directory, send_file
from analyze import analyze
from analyze_cpp import analyze_cpp
from generateTree import generateTree, generateTree_cpp, generateTree_java
from analyzeJava import analyzeJava

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('app.html')


@app.route('/save_codeJava', methods=['GET', 'POST'])
def save_codeJava():
    code = request.form.get('code')
    res = analyzeJava(code)
    return res


@app.route('/save_code', methods=['GET', 'POST'])
def save_code():
    code = request.form.get('code')
    res = analyze(code)
    return res


# 生成测试用例cpp
@app.route('/save_code_cpp', methods=['GET', 'POST'])
def save_code_cpp():
    code = request.form.get('code')
    res = analyze_cpp(code)
    return res


# 生成if树
@app.route('/generate_tree', methods=['POST'])
def generate_tree():
    # 生成图片
    code = request.form.get('code')
    generateTree(code)
    # 图片路径
    image_url = '/static/images/ast_tree.png'
    return jsonify(image_url=image_url)


# 生成if_cpp树
@app.route('/generate_tree_cpp', methods=['POST'])
def generate_tree_cpp():
    # 生成图片
    code = request.form.get('code')
    generateTree_cpp(code)
    # 图片路径
    image_url = '/static/images/ast_tree_cpp.png'
    return jsonify(image_url=image_url)


# 生成if_java树
@app.route('/generate_tree_java', methods=['POST'])
def generate_tree_java():
    # 生成图片
    code = request.form.get('code')
    generateTree_java(code)
    # 图片路径
    image_url = '/static/images/ast_tree_java.png'
    return jsonify(image_url=image_url)


# 下载测试用例
@app.route('/downloadCase', methods=['POST'])
def downloadCase():
    testCase = request.form.get('testCase')
    print(testCase)

    # 将 testCase 写入临时文件
    temp_filename = "temp_test_case.txt"
    with open(temp_filename, "w") as file:
        file.write(testCase)

    # 将文件作为响应发送给客户端
    return send_file(temp_filename, as_attachment=True, download_name="test_case.txt")


if __name__ == '__main__':
    app.run()
